package com.wnhz.work.yz.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.WuLiuBean;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.SkillBookPop;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Wuliu2Activity extends BaseActivity implements View.OnClickListener {
    private RecyclerView recycler;
    private String budget_id = "";

    private RecyclerView tianjia;
    private ImageView add_img;
    private List<String> imgUrl = new ArrayList<>();

    private Myadapter2 myadapter2;

    class Myadapter2 extends BaseRVAdapter {

        /**
         * 构造器
         *
         * @param context 上下文
         * @param list    数据集合
         */
        public Myadapter2(Context context, @NonNull List list) {
            super(context, list);
        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.dialog_add_tupian;
        }

        @Override
        public void onBind(BaseViewHolder holder, final int position) {
            x.image().bind(holder.getImageView(R.id.add_tu), imgUrl.get(position));
            holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    imgUrl.remove(position);
                    Myadapter2.this.notifyDataSetChanged();
                    add_img.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:
                Bitmap bm = null;
                ContentResolver resolver = getContentResolver();

                if (null != data) {
                    Uri uri = data.getData();
                    String imagePath = AlbumImagePath.getPath(this, uri);
                    updateImage(imagePath, uri);

                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {
                    File tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    System.out.println("拍照的路径=====：" + imagePath);

                    File file = new File(imagePath);
                    if (!file.exists()) {
                        return;
                    }
                    updateImage(imagePath, uri);
                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;

        }
    }

    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }


        if (imgUrl.size() < 4) {
            imgUrl.add(imagePath);
            myadapter2.notifyDataSetChanged();
        }
        if (imgUrl.size() >= 4) {
            add_img.setVisibility(View.GONE);
        } else {
            add_img.setVisibility(View.VISIBLE);
        }
        Log.e("img", imgUrl.size() + "");
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public void showPopmenu(View v) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        menuWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        lp = getWindow().getAttributes();
        // lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }

    private String imageName = "";
    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;


        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);
                    break;

                default:
                    break;
            }
        }
    };
    private LinearLayout edit_up;
    private EditText content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wu_liu_list);
        tianjia = (RecyclerView) findViewById(R.id.tianjia);
        tianjia.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false));
        myadapter2 = new Myadapter2(this, imgUrl);
        tianjia.setAdapter(myadapter2);
        content = (EditText) findViewById(R.id.content);
        add_img = (ImageView) findViewById(R.id.add_img);
        add_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopmenu(v);
            }
        });
        edit_up = (LinearLayout) findViewById(R.id.edit_up);
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("安装进度");
        if (getIntent().getIntExtra("isUp", 0) == 1) {
            edit_up.setVisibility(View.VISIBLE);
            TextView submit = (TextView) findViewById(R.id.submit);
            submit.setText("完成");
            submit.setVisibility(View.VISIBLE);
            submit.setOnClickListener(this);
            title.setText("上传进度");
        }


        budget_id = getIntent().getStringExtra("budget_id");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        upLoad();
    }

    private List<WuLiuBean.InfoEntity> info1 = new ArrayList<>();

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", budget_id);
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, "" + value + "\n");
            }
        }
        showDialog();
        XUtil.Post(Url.DECORATE_LOOKPROGRESS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    super.onSuccess(result);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        WuLiuBean bean = gson.fromJson(result, WuLiuBean.class);
                        info1 = bean.getInfo();
                        initData();
                    } else {
                        String info = jsonObject.optString("info");
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();

            }
        });
    }

    private void initData() {
        recycler.setAdapter(new BaseRVAdapter(this, info1) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_wuliu;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                RecyclerView recyclerView = holder.getView(R.id.recycler);
                recyclerView.setLayoutManager(new LinearLayoutManager(Wuliu2Activity.this, LinearLayoutManager.HORIZONTAL, false));
                holder.setTextView(R.id.time, info1.get(position).getAdd_time());
                holder.setTextView(R.id.content, info1.get(position).getContent());


                recyclerView.setAdapter(new BaseRVAdapter(Wuliu2Activity.this, info1.get(position).getImg()) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_wuliu_img;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, int position2) {
                        x.image().bind(holder.getImageView(R.id.img), info1.get(position).getImg().get(position2));
                    }

                });


            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                if ("".equals(content.getText().toString().trim())) {
                    MyToast("请输入内容");
                    return;
                }
                if (imgUrl.size() == 0) {
                    MyToast("请添加图片");
                    return;
                }
                upLoadUp();
                break;
        }
    }

    private void upLoadUp() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        for (int i = 0; i < imgUrl.size(); i++) {
            String targetPath = imgUrl.get(i);
            //调用压缩图片的方法，返回压缩后的图片path
            String compressImage = BitnapUtils.compressImage(targetPath, targetPath, 30);
            File compressedPic = new File(compressImage);
            map.put("files" + i, compressedPic);
            Log.e("-----", compressedPic + "----" + compressImage);
        }

        map.put("content", content.getText());
        map.put("orderid", budget_id);
        showDialog();
        XUtil.Post(Url.DECORATE_UPLOADPROGRESS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        MyToast(info);
                        finish();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });


    }
}
